package daily.year2024.m10;

import java.util.HashMap;
import java.util.Map;

/**
 * No560.和为k的子数组
 *
 * @author wjs 2024/10/31
 */
public class d30 {
    //暴力解法：前缀和
    class Solution1 {
        public int subarraySum(int[] nums, int k) {
            int n = nums.length, res = 0;
            int[] sums = new int[n];

            for(int i=0;i < n;i++) {
                sums[i] = nums[i];
                if(nums[i] == k) {
                    res++;
                }
                for(int j=0;j < i;j++) {
                    sums[j] += nums[i];
                    if(sums[j] == k) {
                        res++;
                    }
                }
            }
            return res;
        }
    }

    //解法2：数学公式转换+前缀和+map
    //其实是一种另类的两数相加
    class Solution2 {
        public int subarraySum(int[] nums, int k) {
            int n = nums.length, sum = 0, res = 0;
            Map<Integer,Integer> map = new HashMap<>();
            map.put(0,1);
            for(int i=0;i < n;i++) {
                sum += nums[i];
                if(map.containsKey(sum - k)) {
                    res += map.get(sum-k);
                }
                map.put(sum,map.getOrDefault(sum,0)+1);
            }
            return res;
        }
    }
}
